<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="/WEB-INF/common/urls.jsp"/>
<html lang="zh-CN">
<head>
    <title>${applicationScope.PROJECT_NAME}-用户图书管理</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, shrink-to-fit=no">
    <%--图标icon--%>
    <link rel="icon" href="${pageContext.request.contextPath}/favicon.ico" type="image/ico">
    <link rel="stylesheet"
          href="${pageContext.request.contextPath}/lib/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/global.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/main.css">
    <script src="${pageContext.request.contextPath}/lib/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js"></script>
    <script src="${pageContext.request.contextPath}/lib/jquery-3.5.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/toast-manager.js"></script>
    <script>
        $(() => {
            /* 分页按钮点击时将条件加入url参数 */
            $('.page-link').each((index, element) => {
                const $link = $(element)
                const originalHref = $link.attr('href')

                $link.on('click', e => {
                    e.preventDefault()

                    // 解析原始href中的URL和参数
                    const url = new URL(originalHref, window.location.origin)
                    const params = url.searchParams

                    // 获取当前页面的参数
                    const currentParams = new URLSearchParams(window.location.search)

                    // 将当前页面的参数添加到新URL中，但不覆盖链接中已有的参数
                    currentParams.forEach((value, key) => {
                        if (!params.has(key)) {
                            params.append(key, value)
                        }
                    })

                    // 设置新的搜索参数
                    url.search = params.toString()

                    // 跳转到新的URL
                    window.location.href = url.toString()
                })
            })

            /* 借阅按钮点击事件 */
            $('.borrow-btn').on('click', function () {
                const $button = $(this)
                const bookId = $(this).data('book-id')
                $.ajax({
                    url: '${userUrl}/borrow',
                    type: 'GET',
                    data: {bookId},
                    success: data => {
                        const parsedData = JSON.parse(data);
                        const {book, message, isSuccess} = parsedData;

                        if (book?.availableCopies !== undefined) {
                            $button.closest('tr').find('.available-copies').text(book.availableCopies);
                            showToast(message, isSuccess);
                        } else {
                            console.error('返回的数据格式不正确');
                            showToast('借阅操作出现问题，请稍后再试。', false);
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error('借阅失败:', error);
                    }
                });
            });

            /* 归还按钮点击事件 */
            $('.return-btn').on('click', function () {
                const $button = $(this)
                const bookId = $(this).data('book-id')
                $.ajax({
                    url: '${userUrl}/return',
                    type: 'GET',
                    data: {bookId},
                    success: data => {
                        const parsedData = JSON.parse(data);
                        const {book, message, isSuccess} = parsedData;

                        if (book?.availableCopies !== undefined) {
                            $button.closest('tr').find('.available-copies').text(book.availableCopies);
                            showToast(message, isSuccess);
                        } else {
                            console.error('返回的数据格式不正确');
                            showToast('借阅操作出现问题，请稍后再试。', false);
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error('归还失败:', error);
                    }
                })
            })

            /* 选中图书计数功能 */
            $('.select-checkbox').on('change', function () {
                const selectedCount = $('.select-checkbox:checked').length
                $('#selectedCount').text(selectedCount)
            })

            /* 批量借阅功能 */
            $('#batchDeleteBtn').on('click', async function () {
                const $checkedBoxes = $('.select-checkbox:checked')

                if ($checkedBoxes.length === 0) {
                    showToast('请先选择要借阅的图书', false)
                    return
                }

                const borrowBook = async (bookId) => {
                    try {
                        const response = await $.ajax({
                            url: '${userUrl}/borrow',
                            type: 'GET',
                            data: {bookId}
                        })

                        const parsedData = JSON.parse(response)

                        // 检查返回的数据结构
                        if (parsedData && parsedData.book && parsedData.book.availableCopies !== undefined) {
                            // 更新表格中对应图书的可用副本数
                            $('.select-checkbox[data-book-id="' + bookId + '"]')
                                .closest('tr')
                                .find('.available-copies')
                                .text(parsedData.book.availableCopies)

                            return {
                                success: parsedData.isSuccess,
                                message: parsedData.message
                            }
                        } else {
                            console.error('返回的数据格式不正确:', parsedData)
                            return {
                                success: false,
                                message: '借阅操作出现问题，请稍后再试'
                            }
                        }
                    } catch (error) {
                        console.error('借阅失败:', error)
                        return {
                            success: false,
                            message: '借阅请求失败'
                        }
                    }
                }

                // 禁用批量借阅按钮，防止重复点击
                const $batchBtn = $(this)
                $batchBtn.prop('disabled', true)

                try {
                    let successCount = 0
                    let failCount = 0

                    // 遍历所有选中的图书，依次借阅
                    for (const checkbox of $checkedBoxes) {
                        const bookId = $(checkbox).data('book-id')
                        const result = await borrowBook(bookId)

                        if (result.success) {
                            successCount++
                        } else {
                            failCount++
                            console.error('借阅失败，图书ID:', bookId)
                        }
                    }

                    // 操作完成后显示结果
                    showToast('批量借阅完成：' + successCount + '本成功，' + failCount + '本失败', successCount > 0)

                    // 清除所有选中状态
                    $('.select-checkbox').prop('checked', false)
                    $('#selectedCount').text('0')

                } catch (error) {
                    console.error('批量借阅过程出错:', error)
                    showToast('批量借阅过程出现错误，请重试', false)
                } finally {
                    // 最后要记得启用按钮
                    $batchBtn.prop('disabled', false)
                }
            })

        })
    </script>
</head>

<body>
<header class="navbar navbar-expand-lg navbar-dark bg-body-secondary">
    <div class="container-fluid">
        <a class="navbar-brand navbar-logo" href="#">
            <svg class="logo" width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
                <path d="M10,5 L30,5 L35,10 L35,35 L5,35 L5,10 L10,5" fill="none" stroke="#1E88E5" stroke-width="2"/>
                <path d="M10,5 L10,10 L5,10" fill="none" stroke="#1E88E5" stroke-width="2"/>
                <path d="M12,15 L28,15 M12,20 L28,20 M12,25 L28,25 M12,30 L28,30" stroke="#1E88E5" stroke-width="1.5"/>
            </svg>
            <span>${applicationScope.PROJECT_NAME}</span>
        </a>
    </div>
</header>

<main class="main">
    <!-- 侧边栏 -->
    <div class="sidebar bg-light pt-3">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="${userUrl}/view/notice">公告通知</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="${userUrl}/view/book">图书查看</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="${userUrl}/view/borrow_record">借阅记录</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="${publicUrl}/logout">退出登录</a>
            </li>
        </ul>
    </div>

    <!-- 主体部分 -->
    <div class="main-content">
        <%--    <h2 class="mb-4">订单查询</h2>--%>
        <!-- 查询表单 -->
        <form class="mb-4" method="get" action="${userUrl}/books_condition">
            <div class="row g-3">
                <div class="col-md-3">
                    <label for="title" class="form-label">图书标题</label>
                    <input type="text" class="form-control" id="title" name="title">
                </div>
                <div class="col-md-3">
                    <label for="author" class="form-label">作者</label>
                    <input type="text" class="form-control" id="author" name="author">
                </div>
                <div class="col-md-3">
                    <label for="isbn" class="form-label">ISBN</label>
                    <input type="text" class="form-control" id="isbn" name="isbn">
                </div>
                <div class="col-md-3">
                    <label for="categoryName" class="form-label">图书类别</label>
                    <select class="form-select" id="categoryName" name="categoryName">
                        <option value="">全部</option>

                        <c:forEach var="category" items="${categoryList}">
                            <option value="${category.categoryName}">${category.categoryName}</option>
                        </c:forEach>

                    </select>
                </div>
            </div>
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">查询</button>
                <button type="reset" class="btn btn-secondary">重置</button>
            </div>
        </form>

        <div class="d-flex mb-3 align-items-end">
            <button id="batchDeleteBtn" class="btn btn-primary">批量借阅</button>
            <span class="ms-3">已选中 <span id="selectedCount">0</span> 本图书</span>
        </div>

        <!-- 订单表格 -->
        <table class="table table-bordered table-striped table-hover">
            <thead>
            <tr>
                <th>#</th>
                <th>图书ID</th>
                <th>标题</th>
                <th>作者</th>
                <th>出版社</th>
                <th>出版日期</th>
                <th>ISBN</th>
                <th>分类号</th>
                <th>类别</th>
                <th>可用副本数</th>
                <th style="width: 134px">操作</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach var="item" items="${list}">
                <tr>
                    <td><input class="form-check-input select-checkbox" type="checkbox" data-book-id="${item.bookId}">
                    </td>
                    <td>${item.bookId}</td>
                    <td>${item.title}</td>
                    <td>${item.author}</td>
                    <td>${item.publisher}</td>
                    <td>${item.publishDate}</td>
                    <td>${item.isbn}</td>
                    <td>${item.classificationNumber}</td>
                    <td>${item.categoryName}</td>
                    <td class="available-copies">${item.availableCopies}</td>
                    <td>
                        <button class="borrow-btn btn btn-sm btn-primary" data-book-id="${item.bookId}">借阅</button>
                        <button class="return-btn btn btn-sm btn-success" data-book-id="${item.bookId}">归还</button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
        <%-- 分页 --%>
        <c:set var="pageNum" value="${param.pageNum == null ? 1 : param.pageNum}"/>
        <ul class="pagination">
            <li class="page-item">
                <a class="page-link" href="${userUrl}/books_condition?pageNum=${pageNum - 1}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <c:forEach var="itemPageNum" begin="1" end="${pageCount}">
                <li class="page-item">
                    <a class="page-link" href="${userUrl}/books_condition?pageNum=${itemPageNum}">
                            ${itemPageNum}
                    </a>
                </li>
            </c:forEach>
            <li class="page-item">
                <a class="page-link" href="${userUrl}/books_condition?pageNum=${pageNum + 1}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </div>
</main>
<jsp:include page="/footer"/>
</body>
</html>